package com.ds.lens.collector.receive.handler;


import com.ds.lens.collector.receive.service.CompositService;
import com.ds.lens.collector.receive.service.dao.entity.LensApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @author ethan
 */
@Slf4j
public abstract class AbstractHandler implements Handler {

    @Autowired
    CompositService compositService;


    @Override
    public HandlerResultWrapper handle(String jsonStr, RequestInfo requestInfo) {
        HandlerResultWrapper handlerResultWrapper = null;
        try {
            if (requestInfo == null) {
                log.warn("Ignore handle request info, requestInfo is null.");
                return null;
            }
            String appKey = requestInfo.getAppKey();
            if (enableValid()) {
                if (StringUtils.isEmpty(appKey)) {
                    log.warn("Ignore handle data, agent appKey is empty.");
                    handlerResultWrapper = getHandlerResultWrapper("Lens-App-Key can not be empty.");
                    return handlerResultWrapper;
                }
                LensApplication app = compositService.getAppByAppKey(appKey);
                if (app == null) {
                    log.warn("Ignore handle this app data, appKey [{}] invalid.", appKey);
                    handlerResultWrapper = getHandlerResultWrapper("Illegal Lens-App-Key");
                    return handlerResultWrapper;
                } else {
                    requestInfo.setAppId(app.getId());
                }
            }

            return handleData(jsonStr, requestInfo);
        } catch (Exception e) {
            log.error("handle data failure.", e);
            handlerResultWrapper = getHandlerResultWrapper("No Lens-App-Key");
        }
        return handlerResultWrapper;
    }

    private HandlerResultWrapper getHandlerResultWrapper(String s) {
        HandlerResultWrapper handlerResultWrapper;
        handlerResultWrapper = new HandlerResultWrapper();
        handlerResultWrapper.setResult(s);
        return handlerResultWrapper;
    }

    protected boolean enableValid() {
        return true;
    }


    protected abstract HandlerResultWrapper handleData(String jsonStr, RequestInfo requestInfo);


}
